package com.woniu.tmsvehicle.consumer;

import com.rabbitmq.client.Channel;
import com.woniu.tmscommons.entity.Driver;
import com.woniu.tmscommons.entity.Vehicle;
import com.woniu.tmsvehicle.config.RabbitConfig;
import com.woniu.tmsvehicle.mapper.DriverMapper;
import com.woniu.tmsvehicle.mapper.VehicleMapper;
import com.woniu.tmsvehicle.service.DriverService;
import com.woniu.tmsvehicle.service.VehicleService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@Component
public class RefreshConsumer {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private DriverService driverService;

    @Resource
    private DriverMapper driverMapper;
    @Resource
    private VehicleMapper vehicleMapper;
    @Resource
    private VehicleService vehicleService;



    @RabbitListener(queues = RabbitConfig.REFRESH_QUEUE_NAME)
    public void received(String msg, Channel channel, Message message){
        System.out.println("接收refresh的消息："+msg);
        try {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        int id = Integer.parseInt(msg.split("-")[3]);
        String[] split = msg.split("-");
        if(split[0].equals("driver")){
            Driver driver = driverMapper.selectById(Integer.parseInt(split[3]));
            redisTemplate.opsForValue().set("driver-"+split[3],driver);
            return;
        }
        if(split[0].equals("drivers")){
            List<Driver> drivers = driverMapper.selectList(null);
            redisTemplate.opsForValue().set("drivers",drivers);
            return;
        }

        if(split[0].equals("vehicle")){
            Vehicle vehicle = vehicleMapper.selectById(Integer.parseInt(split[3]));
            redisTemplate.opsForValue().set("vehicle-"+split[3],vehicle);
            return;
        }
        if(split[0].equals("vehicles")){
            List<Vehicle> vehicles = vehicleMapper.findAll();
            redisTemplate.opsForValue().set("vehicles",vehicles);
            return;
        }
    }
}
